
pub mod site_config;
pub mod app_config;
pub mod site_base;

use serde::{Serialize, Deserialize};
use site_config::SiteConfig;
use crate::util::app_with_site_config::AppWithSiteConfig;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
pub struct AppListConfig {
  pub site_list: Vec<SiteConfig>,
}

impl AppListConfig {
  pub fn init_from_file(file_path: &str) -> AppListConfig {
    crate::util::yaml_helper::read_yaml_file::<AppListConfig>(file_path)
  }

  pub fn find_target_site(&self, site_name: &str) -> Option<&SiteConfig> {
    self.site_list.iter().find(|site_config| {
      site_config.get_site_name().eq(site_name)
    })
  }

  pub fn get_app_with_site_vec(&self) -> Vec<AppWithSiteConfig> {
    self.site_list.iter().flat_map(|site_config| {
      site_config.app_list.iter().map(|app_config| {
        AppWithSiteConfig::new(app_config.clone(), site_config.clone())
      })
    }).collect()
  }
}

static SITE_LIST_CONFIG: once_cell::sync::OnceCell<AppListConfig> = once_cell::sync::OnceCell::new();

pub fn init_global_site_list_config(app_list_file_path: &str) {
    let app_list_config = AppListConfig::init_from_file(app_list_file_path);
    SITE_LIST_CONFIG.set(app_list_config).expect("set SITE_LIST_CONFIG error");
}

pub fn get_global_site_list_config() -> &'static AppListConfig {
    SITE_LIST_CONFIG.get().expect("get SITE_LIST_CONFIG error")
}
